package cn.edu360;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;

import cn.edu360.bean.Request;
import cn.edu360.bean.Response;
import cn.edu360.bean.ResultBean;

public class Server {

	public static void main(String[] args) {
		try {
			ServerSocket serverSocket = new ServerSocket(8888);
			System.out.println("服务器端启动了");
			while (true) {
				Socket accept = serverSocket.accept();
				ObjectInputStream ois = new ObjectInputStream(accept.getInputStream());
				Request req = (Request) ois.readObject();
				// 返回结果
				Response response = new Response();
				try {
					Class<?> forName = Class.forName(req.getClassName());
					Object newInstance = forName.newInstance();
					Method method = forName.getMethod(req.getMethodName(), req.getClassType());
					ResultBean resultBean = (ResultBean) method.invoke(newInstance, req.getValue());
					response.setResultBean(resultBean);
					response.setStatus("200");
				} catch (Exception e) {
					e.printStackTrace();
					response.setStatus("500");
				}
				ObjectOutputStream oos = new ObjectOutputStream(accept.getOutputStream());
				oos.writeObject(response);
				oos.flush();
                //释放资源
				accept.shutdownInput();
				accept.shutdownOutput();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
